﻿/* 
 * This file is part of the Coffee Survey Framework - http://coffee.codeplex.com
 */
using System.Text;
using System.Web.UI.WebControls;
using System.Data;

namespace Coffee.Utils
{
    public class JsonDropdownMapper : DataBoundControl
    {
        string textfield, valuefield;
        StringBuilder sb = new StringBuilder();
        object datasource;

        public string DataTextField { get { return textfield; } set { textfield = value; } }
        public string DataValueField { get { return valuefield; } set { valuefield = value; } }
        public override object DataSource { get { return datasource; } set { datasource = value; } }

        /// <summary>
        /// Build the JSON string from the data
        /// </summary>
        public void DataBind()
        {
            DataTable dt = (DataTable)datasource;
            sb.Append("{options:[");
            if (dt != null)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    sb.Append(string.Format("{{text:'{0}',value:'{1}'}},", dr[textfield].ToString().Replace("'", "\\'"), dr[valuefield].ToString()));
                }
                if (dt.Rows.Count > 0)
                    sb.Remove(sb.Length - 1, 1);
            }
            sb.Append("]};");
        }

        public override string ToString()
        {
            return sb.ToString();
        }
    }

}
